import axios from 'axios'

// 用于存储等待中的请求队列
let refreshQueue = []
// 标记是否正在刷新token
let isRefreshing = false

// 创建axios实例
const instance = axios.create()

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('accessToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config

    // 如果响应状态码是401（未授权）且不是刷新token的请求
    if (error.response?.status === 401 && !originalRequest._retry) {
      // 如果已经在刷新token，将请求加入队列
      if (isRefreshing) {
        return new Promise(resolve => {
          refreshQueue.push(() => {
            originalRequest.headers.Authorization = `Bearer ${sessionStorage.getItem('accessToken')}`
            resolve(instance(originalRequest))
          })
        })
      }

      originalRequest._retry = true
      isRefreshing = true

      try {
        // 请求刷新token
        const response = await axios.post('/api/refresh', {}, {
          withCredentials: true
        })

        const { accessToken } = response.data
        sessionStorage.setItem('accessToken', accessToken)

        // 更新原始请求的token
        originalRequest.headers.Authorization = `Bearer ${accessToken}`

        // 执行队列中的请求
        refreshQueue.forEach(callback => callback())
        refreshQueue = []

        return instance(originalRequest)
      } catch (error) {
        // 刷新token失败，清除token和cookie
        sessionStorage.removeItem('accessToken')
        sessionStorage.removeItem('username')
        document.cookie = 'refreshToken=; Max-Age=0; Path=/;'
        window.location.href = '/login'
        return Promise.reject(error)
      } finally {
        isRefreshing = false
      }
    }

    return Promise.reject(error)
  }
)

// 替换全局的axios
axios.defaults.baseURL = '/api'
Object.assign(axios, instance)

export default instance